# @Time    :2025/4/3 11:56
# 创建生成器


# 1）使用推导式创建生成器
# generator = (x for x in range(5))  # 创建生成器
# print(generator)
# for x in generator:
#     print(x)


# for i in range(6):
#     print(i)

# 使用函数创建生成器
# def fibo():
#     a, b = 0, 1
#     while True:
#         yield b
#         a, b = b, a + b
#
#
# f = fibo()
# print(next(f))
# print(next(f))
# print(next(f))
# print(next(f))


# 如果我们要获取生成器中 return 的值，我们需要捕获 StopIteration异常

def fibo(n):
    a, b, counter = 0, 1, 0
    while counter < n:
        yield b
        a, b, counter = b, a + b, counter + 1
    return "done22"#当生成器函数执行到 return 语句时，它会引发一个 StopIteration 异常，并且 return 的值会作为该异常的 value 属性传递


f = fibo(10)
try:
    while True:
        print(next(f))
except StopIteration as result:
    print("StopIteration1", result)
